package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /*
     * 新增菜品和对应的口味数据
     * */
    @Override
    @Transactional//因为这个方法要对菜品数据表和口味数据表两张表进行操作，因此我们要保证这两张表的操作同步，因此我们把这两张表的操作捆绑成为一个事务
    public void saveWIthFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //我们在这里不使用用公共字段填充
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateTime(LocalDateTime.now());

        //向菜品表插入数据
        dishMapper.insert(dish);
        //获取Insert操作为dish生成的主键值，这块要去看dishMapper配置，他并不是直接获取的，而是通过XML中的动态SQL的配置完成的
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表中插入N条数据
            dishFlavorMapper.insert(flavors);
        }
    }

    /*
     * 菜品分页查询
     * */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pagequary(dishPageQueryDTO);
        Long total = page.getTotal();
        List<DishVO> result = page.getResult();

        return new PageResult(total, result);
    }

    /*
    * 菜品的批量删除
    * */
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否可以删除------是否存在起售中的菜品
        for(Long id:ids)
        {
             Dish dish = dishMapper.getByid(id);
             if (dish.getStatus()== StatusConstant.ENABLE)//起售
             {
                 //当前菜品处于起售状态，不可以删除
                 throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
             }
        }
        //判断当前菜品是否可以删除------是否存在捆绑在套餐中的菜品
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(ids);
        if(setmealIds!=null && setmealIds.size()>0)
        {
            //当前菜品已经被套餐绑定，不可以进行删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //进行删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteByid(id);
            //进行删除菜品表中的口味数据
            //在这里我们也不查有无口味数据，我们就直接进行删除，如果有就删除了，如果没有也无所谓
            dishFlavorMapper.deleteByid(id);
        }
    }

    /*
    * 根据Id查询菜品和对应的口味数据
    * */
    @Override
    public DishVO getByidWithflavor(Long id) {

        //先根据ID查询菜品数据
        Dish dish = dishMapper.getByid(id);

        //再根据ID查询口味数据
        List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishid(id);

        //封装到一个DishVO对象中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        //BeanUtils.copyProperties(dishFlavors,dishVO);

        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /*
    * 修改菜品
    * */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //修改口味表的信息(这里我们不修改，因为太麻烦，采用先删除再插入的方式)
        //删除
        dishFlavorMapper.deleteByid(dishDTO.getId());
        //插入
        List<DishFlavor> flavors= dishDTO.getFlavors();
        //判断此时还是否有口味
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表中插入N条数据
            dishFlavorMapper.insert(flavors);
        }

    }

    @Override
    public List<Dish> list(Long catrgoryId) {
        Dish dish = Dish.builder()
                .categoryId(catrgoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishid(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
